#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年6月6日

@author: chenyongbing
'''

import os,sys
from hive_service import ThriftHive
from hive_service.ttypes import HiveServerException
from thrift.transport import TSocket
from thrift import Thrift
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
class ConnectHive(object):
    '''
    classdocs
    '''


    def __init__(self,host='localhost',port=10002):
        '''
        Constructor
        '''
        self.host = host
        self.port = port
        self.client = self.conn()
    def conn(self):
        socket = TSocket.TSocket(self.host, self.port)
        transport = TTransport.TBufferedTransport(socket)
        protocol = TBinaryProtocol.TBinaryProtocol(transport)
        client = ThriftHive.Client(protocol)
        transport.open()
        return client
    
    def execute(self,query):
        self.client.execute(query)
        out = self.client.fetchAll()
        return out
    
    def selectAll(self,query):
        self.client.execute(query)
        out = self.client.fetchAll()
        return out
    def selectOne(self,query):
        self.client.execute(query)
        out = self.client.fetchOne()
        return out
        
    def selectCount(self,query):
        print query
        self.client.execute(query)
        out = self.client.fetchAll()
        return len(out)
if __name__=='__main__':
#     socket = TSocket.TSocket('192.168.1.201', 10002)
#     transport = TTransport.TBufferedTransport(socket)
#     protocol = TBinaryProtocol.TBinaryProtocol(transport)
#     client = ThriftHive.Client(protocol)
#     sql = 'select  mac,max(day) from history_role_test group by mac'
#     transport.open()
#     r = client.execute(sql)
#     out = client.fetchAll()
    #sql = 'select  mac,max(day) from history_role_test group by mac'
    sql = 'select mac,day from history_role_test where day="2015-01-02" and role in (1,-1,3,10) limit 10'
    print sql
    myConnectHive = ConnectHive('192.168.1.201',10002)
    print myConnectHive
    out = myConnectHive.selectAll(sql)
    for line in out:
        print line